<template>
  <div class="dwWarnEarthWrap classMain">
    <NavBar
      :title="'预警地图'"
      :cityName="cityName"
      :areaName="areaName"
      v-show="!dwWarnEarthDetailShow"
      :text="'返回'"
      :SeveralMenus="'1'"
      @clicksPopul="clicksPopul"
    ></NavBar>
    <div
      v-show="!dwWarnEarthDetailShow"
      id="map"
      style="width: 100%; height: 100%"
    ></div>

    <div
      v-show="!dwWarnEarthDetailShow"
      class="sideBtn"
      @click="toPage('disasterWarning?tab=1')"
    >
      <img src="../assets/dwList.png" alt="" />
      <div>预警列表</div>
    </div>

    <div
      v-show="!dwWarnEarthDetailShow"
      class="sideBtn second"
      @click="toPage('staDisasterList')"
    >
      <img src="../assets/Earlywarningmap/tongji.png" alt="" />
      <div>预警统计</div>
    </div>

    <detail
      v-if="dwWarnEarthDetailShow"
      :nowClickItem="nowClickItem"
      @detailBack1="detailBack1"
    ></detail>
    <comArea
      v-if="showArea"
      @closeEmit="showArea = false"
      :arr="arr1"
      @confirmEmit="confirmEmitMet"
    >
    </comArea>
  </div>
</template>
<script type="text/javascript">
import meteoroDisasterWarningApi from "@/service/disasterWarning.js";
import dwPicture from "@/components/mixins/dwPicture.js";
import areaInfo from "@/components/common/areaInfo.js";
import forecast from "@/assets/forecast/baoyu-blue.png";
import dwWarnEarthDetail from "@/components/disasterWarning/dwWarnEarthDetail.vue";
import detail from "@/components/disasterWarning/detail.vue";
import map from "@/util/map.js";
import comArea from "@/components/common/area.vue";
export default {
  mixins: [dwPicture],
  data() {
    return {
      index: 0,
      dwInfo: {},
      page: {
        limit: 2000,
        page: 1,
      },
      listData: [],
      maplist: [],
      formatPosiArr: [],
      alarmSendtimeStart: "",
      alarmSendtimeEnd: "",
      dw: "",
      showArea: false,
      map: null,
      forecast: forecast,
      dwWarnEarthDetailShow: false,
      nowClickItem: {},
      arr1: [],
      cityName: "",
      areaName: "",
    };
  },
  mounted() {
    this.cityName = this.$store.getters.location[1].name;
    this.areaName = this.$store.getters.location[2].name;
    map.init().then((res) => {
      //初始化地图
      this.initMap([112.5659408833, 37.870682192588]);
    });
  },
  watch: {},
  components: {
    dwWarnEarthDetail,
    detail,
    comArea,
  },
  destroyed: function () {
    this.map.remove();
    // 离开页面生命周期函数
    // this.websocketclose()
  },
  methods: {
    confirmEmitMet(value) {
      var _this = this;
      _this.showArea = false;
      _this.$util.Convertlatitude(value).then((result) => {
        _this.location = [result[0], result[1]];
        _this.map.setCenter(_this.location);
        _this.map.setZoom(9);
        _this.cityName = value[1].name;
        _this.areaName = value[2].name;
        _this.arr1 = [value[1].name, value[2].name];
      });
    },
    clicksPopul() {
      this.showArea = true;

      this.arr1 = [this.cityName, this.areaName];
    },
    getDateStr(AddDayCount) {
      var dd = new Date();
      dd.setDate(dd.getDate() + AddDayCount); //获取AddDayCount天后的日期
      var y = dd.getFullYear();
      var m = dd.getMonth() + 1; //获取当前月份的日期

      var d = dd.getDate();
      d = d < 10 ? "0" + d : d;
      var h = dd.getHours();
      h = h < 10 ? "0" + h : h;
      var minute = dd.getMinutes();
      var second = dd.getSeconds();
      minute = minute < 10 ? "0" + minute : minute;
      second = second < 10 ? "0" + second : second;
      return (
        y +
        "-" +
        (m < 10 ? "0" + m : m) +
        "-" +
        d +
        " " +
        h +
        ":" +
        minute +
        ":" +
        second
      );
    },
    detailBack1() {
      this.alarmSendtimeEnd = this.$util.getTime();

      this.dwWarnEarthDetailShow = false;
    },
    initMap(location) {
      var _this = this;
      _this.$toast.loading({
        message: "加载中...",
        forbidClick: true,
        duration: 0,
      });
      _this.map = new SGMap.Map({
        // 地图绑定的DOM元素ID
        container: "map",
        // 地图样式
        style: "aegis://styles/aegis/Streets-v2",
        // 默认缩放层级
        zoom: 5.5,
        // 地图中心点
        center: location,
        // 地图默认字体
        localIdeographFontFamily: "Microsoft YoHei",
      });

      _this.map.on("load", function (e) {
        _this.$util.initLayerAll("", _this.map);
        _this.$util.searchAll("", _this.map);
        // 绘制标识图层
        _this.initApi();
      
        var a = _this.getDateStr(-1);
        _this.alarmSendtimeEnd = _this.$util.getTime();
        _this.alarmSendtimeStart = a;
        var params1 = {
          startTime: _this.alarmSendtimeStart,
          endTime: _this.alarmSendtimeEnd,
        };
        meteoroDisasterWarningApi
          .Earlywarningmap(params1)
          .then((res) => {
            _this.maplist = res;
            _this.addMarker(_this.map, res);
            // _this.$toast.clear();
          })
          .catch((error) => {});
        //添加监听事件
        _this.map.on("click", function (e) {});
      });
    },

    initApi() {
      var a = this.getDateStr(-3);

      this.alarmSendtimeEnd = this.$util.getTime();
      this.alarmSendtimeStart = a;
      //统计查询预警信息
      var params = {
        alarmSendtimeStart: this.alarmSendtimeStart,
        alarmSendtimeEnd: this.alarmSendtimeEnd,
      };

      meteoroDisasterWarningApi
        .post_tb_alarm_totalAlarm(params)
        .then((res) => {
          this.dwInfo = res;
        })
        .catch((error) => {
          this.$toast.clear();
        });
    },
    toPage(params) {
      this.$router.push(params);
    },
    // 添加Marker点
    addMarker(map, res) {
      res = res.filter((it) => {
        return it.city !== "无" && it.cnty !== "无";
      });
      // 使用 map() 方法改为返回一个 Promise 数组
      const promises = res.map(async (it) => {
        const result = await SGMap.plugin("SGMap.GeocodingTask").then(
            function (res) {
              var geocodingTask = new SGMap.GeocodingTask();
              return geocodingTask.getLocation({
                address: it.city + it.cnty,
                region: "山西",
                isEncode: false,
              });
            }
          );

          it.location = result.location;
          return it;
      });

      (async () => {
        const results = await Promise.all(promises);
       
        var arr = this.$util.getDwType(results);
        arr.forEach((it) => {
       
          var _this = this;
          var el = document.createElement("div");
          el.style.backgroundImage =
            "url(" +
            require(`../assets/Earlywarningmap/yujingmap/${it.imageType}-${it.degree}.png`) +
            ")";
          el.style.width = "35px";
          el.style.height = "30px";
          el.setAttribute("data-name", JSON.stringify(it.location));
          el.setAttribute("data-city", JSON.stringify(it.city + it.cnty));
          el.setAttribute(
            "data-cloor",
            JSON.stringify(it.imageType + it.degree)
          );
          el.style.backgroundSize = "contain";
         
            const marker = new SGMap.Marker({
              element: el,
              anchor: "bottom",
            })
              .setLngLat(it.location)
              .addTo(_this.map);
          this.$toast.clear();

          el.addEventListener("click", async (e) => {
            const dataname = JSON.parse(e.target.getAttribute("data-name"));
            const datacity = JSON.parse(e.target.getAttribute("data-city"));
            const color = JSON.parse(e.target.getAttribute("data-cloor"));
            let alist = arr.find(
              (is) =>
                is.location.toString() === dataname.toString() &&
                datacity === is.city + is.cnty &&
                color === is.imageType + is.degree
            );
            _this.dw = "maps";
            _this.nowClickItem = alist;

            _this.dwWarnEarthDetailShow = true;
          });
        });
        // 处理 results
      })();

      // results 现在是包含所有元素的新数组，每个元素都已经添加了位置信息
    },
  },
};
</script>
<style type="text/css" lang="less" scoped>
.dwWarnEarthWrap {
  width: 100%;
  height: 100%;
  background-color: #ececec;
  .titleArea {
    position: absolute;
    left: 0;
    top: 46px;
    width: 100%;
    height: 90px;
    background: white;
    padding: 10px;
    font-size: 14px;
    box-sizing: border-box;
    z-index: 1;
  }
  .topTipLine {
    margin-bottom: 5px;
  }
  .topTipLineSpan {
    margin-right: 10px;
  }

  .sideBtn {
    position: absolute;
    right: 10px;
    top: 140px;

    width: 55px;
    height: 55px;
    background: #357cff;
    box-shadow: 0px 0px 15px 0px rgba(53, 124, 255, 0.6);
    border-radius: 10px;
    display: flex;
    /* align-items: center; */
    flex-direction: column;
    align-items: center;
    text-align: center;
    img {
      margin-top: 5px;
      width: 20px;
    }
    div {
      color: white;
      text-align: center;
      font-size: 12px;
      margin-top: 5px;
    }
  }
  .sideBtn.second {
    top: 210px;
  }
  .sideBtn.three {
    top: 280px;
  }
}
</style>
